<template>
  <!-- 功率曲线数据 弹窗 -->
  <a-modal
    v-model:open="visible"
    title="功率曲线数据"
    @ok="handleOk"
    destroyOnClose
    :width="1000"
    @cancel="cancel"
    centered
  >
    <a-table
      :dataSource="tableData"
      :columns="columns"
      size="small"
      :scroll="{ x: 'max-content' }"
      @resizeColumn="handleResizeColumn"
      :loading="tableLoading"
      :rowKey="(column) => column"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'stationTfName'">
          <span v-param="record.pdId">{{ record.stationTfName }}</span>
        </template>
      </template>
    </a-table>
    <template #footer>
      <div class="footerBar">
        <a-button
          v-hasPermission="'monitorPowerExportData'"
          class="yellowBtn"
          @click="handleExport"
          :loading="loading"
          >导出</a-button
        >
        <a-button key="submit" type="primary" @click="cancel">关闭</a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup>


import utilsExportFile from "@/utils/exportFile";
import { transformExportData } from "@/utils/common";
import { cloneDeep } from "lodash-es";
const $api = inject("$api");
const props = defineProps({
  detailsDataVisible: {
    type: Boolean,
    default: false,
  },
  chartsTableData: {
    type: Object,
  },
  chartType: {
    type: String,
  },
  branchData: {
    type: String,
  },
});
const prefixStationTfName = {
  total: "总功率",
  total1: "计量点",
};
const visible = ref(props.detailsDataVisible);
const loading = ref(false);
const emits = defineEmits(["update:detailsDataVisible", "getParamCodePage"]);
watch(
  () => props.detailsDataVisible,
  (val) => {
    visible.value = val;
    if (val) {
      initTableData();
    }
  }
);
const exportData = ref([]);
const originColumns = ref([]);
const initTableData = () => {
  originColumns.value = cloneDeep(columns.value); // 保存原始列用于恢复
  if (props.branchData.length) {
    for (const item of props.branchData) {
      columns.value.push({
        title: item.name,
        dataIndex: item.type,
        key: item.type,
        width: 150,
        resizable: true,
        align: "center",
      });
    }
  }
  const chongDianZhuang = props.chartsTableData.flat().filter(item => item.lineType === 7)
  if (chongDianZhuang.length) {
    for (const item of chongDianZhuang) {
      columns.value.push({
        title: item.lineName,
        dataIndex: item.lineName,
        key: item.lineName,
        width: 150,
        resizable: true,
        align: "center",
      });
    }
  }
  // 初始化一个空数组用于存储最终结果
  const newlineData = [];
  // 使用一个对象来跟踪站点和日期的组合
  const resultMap = {};
  // 1-总功率 2-储能功率 3-用户功率 4-SOC
  props.chartsTableData.flat().forEach((item) => {
    const { stationTfName, lineType, lineData, lineName } = item;
    const dataName =
      props.chartType === "normal"
        ? stationTfName
        : prefixStationTfName[props.chartType];
    lineData.forEach((line) => {
      const { dateTime, value, isBuild } = line;
      const key = `${dataName}-${dateTime}`; // 创建唯一标识符
      // 如果这个组合尚未在 resultMap 中存在
      if (!resultMap[key]) {
        resultMap[key] = {
          stationTfName: dataName,
          dateTime,
        };
        newlineData.push(resultMap[key]); // 添加到 newlineData 数组中
      }
      // 根据 lineType 设置相应的值
      if (lineType === 7) {
        // 充电枪数据使用 lineName 作为键
        resultMap[key][lineName] = value;
        resultMap[key][`isBuild${lineName}`] = isBuild;
      } else {
        // 其他类型数据保持原有逻辑
        resultMap[key][lineType] = value;
        resultMap[key][`isBuild${lineType}`] = isBuild;
      }
    });
  });
  tableData.value = newlineData;
  // 以下处理导出数据
  const baseTitle = ["数据来源", "时间", "储能功率", "用户功率", "总功率", "SOC"];
  const branchTitles = props.branchData.length 
    ? props.branchData.map(item => item.name)
    : [];
  const chargingTitles = props.chartsTableData.flat()
    .filter(item => item.lineType === 7)
    .map(item => item.lineName);
  exportData.value = {
    title: [...baseTitle, ...branchTitles, ...chargingTitles],
    list: transformExportData(
      tableData.value,
      columns.value.map((item) => item.key)
    ),
  };
};
const labelCol = { style: { width: "130px" } };
const tableData = ref([]);
const columns = ref([
  {
    title: "数据来源",
    dataIndex: "stationTfName",
    key: "stationTfName",
    width: 150,
    resizable: true,
    align: "center",
  },
  {
    title: "时间",
    dataIndex: "dateTime",
    key: "dateTime",
    width: 180,
    resizable: true,
    align: "center",
  },
  {
    title: "储能功率",
    dataIndex: "2",
    key: "2",
    width: 120,
    resizable: true,
    align: "center",
    customCell: (record, rowIndex, column) =>
      getCustomCellColour(record, rowIndex, column),
  },
  {
    title: "用户功率",
    dataIndex: "3",
    key: "3",
    width: 120,
    resizable: true,
    align: "center",
    customCell: (record, rowIndex, column) =>
      getCustomCellColour(record, rowIndex, column),
  },
  {
    title: "总功率",
    dataIndex: "1",
    key: "1",
    width: 150,
    resizable: true,
    align: "center",
    customCell: (record, rowIndex, column) =>
      getCustomCellColour(record, rowIndex, column),
  },
  {
    title: "SOC",
    dataIndex: "4",
    key: "4",
    width: 150,
    resizable: true,
    align: "center",
    customCell: (record, rowIndex, column) =>
      getCustomCellColour(record, rowIndex, column),
  },
]);
const getCustomCellColour = (record, rowIndex, column) => {
  const { isBuild1, isBuild2, isBuild3, isBuild4 } = record;
  switch (column.dataIndex) {
    case "1":
      if (isBuild1) {
        return {
          style: {
            background: `rgba(244, 63, 94, 0.2)`,
          },
        };
      }
      break;
    case "2":
      if (isBuild2) {
        return {
          style: {
            background: `rgba(244, 63, 94, 0.2)`,
          },
        };
      }
      break;
    case "3":
      if (isBuild3) {
        return {
          style: {
            background: `rgba(244, 63, 94, 0.2)`,
          },
        };
      }
      break;
    case "4":
      if (isBuild4) {
        return {
          style: {
            background: `rgba(244, 63, 94, 0.2)`,
          },
        };
      }
      break;
  }
  /* const { isBuild1, isBuild2, isBuild3, isBuild4 } = record
  if (isBuild1 || isBuild2 || isBuild3 || isBuild4) {
    console.log("[ record ]-101", record, column)
    return {
      style: {
        background: `rgba(244, 63, 94, 0.2)`,
      },
    }
  } */
};
const cancel = () => {
  emits("update:detailsDataVisible", false);
  columns.value = originColumns.value;
};
const tableLoading = ref(false);
const handleExport = async () => {
  loading.value = true;
  const res = await $api.exportCommon(exportData.value);
  loading.value = false;
  utilsExportFile.exportFile(res, `${"功率曲线数据"}.xlsx`);
};
</script>

<style lang="less" scoped>
.ant-table {
  .ant-btn {
    padding: 4px 5px;
  }
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
</style>
